package guser

import (
	"gitee.com/qian/guser/api"
	middlewareJwt "gitee.com/qian/guser/middleware/jwt"
	middleware "gitee.com/qian/guser/middleware/session"
	middlewareToken "gitee.com/qian/guser/middleware/token"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/gconv"
	"strings"
)

func init() {
	register()
}

func MiddlewareCORS(r *ghttp.Request) {
	r.Response.CORSDefault()
	r.Middleware.Next()
}

func register() {
	s := g.Server()
	s.Group("/guser/", func(group *ghttp.RouterGroup) {
		auth := gconv.String(g.Cfg().Get("guser.auth"))
		if strings.Contains(auth, "session") {
			group.Group("/", func(group *ghttp.RouterGroup) {
				group.Middleware(middleware.GUserSessionMiddleware.Ctx)
				group.ALL("/sessionLogin", api.GUserSessionLoginApi.Login)

				group.Group("/", func(group *ghttp.RouterGroup) {
					//需要验证的方法
					group.Middleware(middleware.GUserSessionMiddleware.SessionAuth)
					group.GET("/pingSession", api.GUserPing)
					group.ALL("/sessionLogout", api.GUserSessionLoginApi.Logout)
				})
			})
		}

		if strings.Contains(auth, "token") {
			group.Group("/", func(group *ghttp.RouterGroup) {
				//跨域
				group.Middleware(MiddlewareCORS)
				//token
				group.Middleware(middlewareToken.GUserTokenMiddleware.Ctx)
				group.POST("/tokenLogin", api.GUserTokenLoginApi.Login)

				group.Group("/", func(group *ghttp.RouterGroup) {
					//需要验证的方法
					group.Middleware(middlewareToken.GUserTokenMiddleware.SessionAuth)
					group.GET("/pingToken", api.GUserPing)
					group.ALL("/tokenLogout", api.GUserTokenLoginApi.Logout)
				})
			})
		}

		if strings.Contains(auth, "jwt") {
			group.Group("/", func(group *ghttp.RouterGroup) {
				//跨域
				group.Middleware(MiddlewareCORS)
				//token
				group.Middleware(middlewareJwt.GUserJwtMiddleware.Ctx)
				group.POST("/jwtLogin", api.GUserJwtLoginApi.LoginHandler)

				group.Group("/", func(group *ghttp.RouterGroup) {
					//需要验证的方法
					group.Middleware(middlewareJwt.GUserJwtMiddleware.SessionAuth)
					group.GET("/pingJwt", api.GUserPing)
					group.ALL("/jwtLogout", api.GUserJwtLoginApi.LogoutHandler)
					group.GET("/jwtRefresh", api.GUserJwtLoginApi.RefreshHandler)
				})
			})

		}
	})
}
